import os
from django import http
from django.conf import settings
from django.shortcuts import render
from django.views.generic import View

from alipay import AliPay
from urtils.response_code import RETCODE
from order.models import OrderInfo, OrderGoods
from payment.models import Payment
from urtils.view import LoginRequiredJSONMixin
# Create your views here.


class PaymentStatusView(LoginRequiredJSONMixin, View):
    """保存支付订单"""
    def get(self, request):
        # 获取前端传入的请求参数
        query_dict = request.GET
        data = query_dict.dict()
        # 获取并从请求参数中剔除signature
        signature = data.pop('sign')
        # 创建支付宝支付对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            # app_private_key_string: 内容
            # app_private_key_path: 路径
            app_private_key_string="""-----BEGIN RSA PRIVATE KEY-----
MIIEogIBAAKCAQEAqBy/feKsFTEzUC+VtdEU6Fg4a3BS/Fj79vnpf2/anD1SpIGcs/GcKmEWl5uByNbAbhepheoW54AHR9N8oa6ib0kSUGcpEFO+UsMXbpqGiPbgdg5YPHDH+Ckal4wrNiQ3Fv4gH81L9mLADJn0N7sMVyvLW4pcUCpIeD6nluasc1g/bfyKN3e3yRuARNafgQbbUDx5uKcLmUXcKVJYB21wN20XHyieuW1muHZc9KOWhfVb/b6RY9NtSZ2MJ+HaKraMtOop5U3OOS0bvhVpx/bkHpgMAXpYjN21WPNS8LAe9dpDEommaUxWAcwfXwE4DiKzUDnNvVbNwpKlEmn/F2YJ8wIDAQABAoIBAGrptYLKuGPV4Wtah9yUdrZ4/JCfY7dmo/9i2nOYYDBC8575av4pZwawrhyG4lgm80RQuhgXUq+xhW/ReQ6eMGGT2BjYMo5Wo9Cgj/NgRLUwRHnwD3+IvjP9eBLvKsAI8hwmS6nN90RfcwHQmzciNuvtRywVZzX4XhRSzGQ0mXHUosptBGWmb8mRy1oWfdpCCxL0J5NWB6RxgsifexzXwN1YwMIEgsyBbojavdwoQKY+MIpuel8l1NtGV8ARc4B+V30fCC/Cl/LceVfRBhHnmFmnpAemtQ45zhvTixYWsvScjVZJpPTrMEGk54cS6HGCxr39xAOeXnc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vus1GnITwMq0wXpwQwulrWVhUwbKDWsgsO9wy+Z2hY7BH5Ll0TQwIh9FSPWyEmIzQ6DA+A5k8bCdEXYwwKaJWYIUBKAZPrDEAyE+tbsyPzfWplh5zKujz0tIHSvQqhZlhSct+sIko2Gf5fuJ+oFidLpFYy1rCLDhxoS3Sg53YaG4UH10Zvzcg+sWG9Q9eldPKkwlByq/cvpYglnIcc1pxOUvZu9rykMUGUcUxfErMluuOqFQVo6Ha3XDJyyebmwIDAQAB
-----END PUBLIC KEY-----""",
            sign_type="RSA2",
            debug=settings.ALIPAY_DEBUG
        )
        # 校验这个重定向是否是alipay重定向过来的
        success = alipay.verify(data, signature)
        if success:
            # 保存订单信息
            # 读取order_id
            order_id = data.get('out_trade_no')
            # 读取支付宝流水号
            trade_id = data.get('trade_no')
            # 保存Payment模型类数据
            Payment.objects.create(
                order_id=order_id,
                trade_id=trade_id,
            )
            # 修改订单状态为待评价
            OrderInfo.objects.filter(order_id=order_id, status=OrderInfo.ORDER_STATUS_ENUM['UNPAID']).update(
                status=OrderInfo.ORDER_STATUS_ENUM["UNCOMMENT"]
            )
            # 构造上下文
            context = {
                'trade_id': trade_id,
            }
            return render(request, 'pay_success.html', context)
        else:
            # 订单支付失败，重定向到我的订单
            return http.HttpResponseForbidden("非法请求")


class PaymentView(LoginRequiredJSONMixin, View):
    """支付订单功能"""
    def get(self, request, order_id):
        """
        :param order_id: 当前要支付的订单id
        :return:  返回JSON
        """
        # 查询要支付的订单
        user = request.user
        try:
            order = OrderInfo.objects.get(order_id=order_id, user=user, status=OrderInfo.ORDER_STATUS_ENUM['UNPAID'])
        except OrderInfo.DoesNotExist:
            return http.HttpResponseForbidden('订单信息错误')

        # 创建支付宝支付对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            # app_private_key_string: 内容
            # app_private_key_path: 路径
            app_private_key_string="""-----BEGIN RSA PRIVATE KEY-----
MIIEogIBAAKCAQEAqBy/feKsFTEzUC+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o2kTqLg4ieWkXiBap2q4TMX9+QyNxgLAgi2YMJP1ydyylW+ns4AMHE0QcG6YTQ7lRXLDS303Zg9V4l3iuaJV2W9NhlNZf5/tUqadHzSfUox/sOSj2YKpN/9qQ0bIuAsw8wKBgF6N+qlRKznraHdPKmcHX1Vhh/3eSFsm7ws/5csnigUS6xGym0dGHzvPD+sLKEwg+wbc0XHgiFPDruVtOQHfqHF884D3mj9lnlRk2951EkUctzI6x5/5sRJHWGHRTZ9pxdTOUEsZQhesCAYyAlR5BemInlC5GAh0Tp7Y101/kNw5AoGAfi9R+22VMeLwTaTIfOeUKfAKpadLHL9kTTOp43N/uWpfcLGMReayYrtii0GdVr+6lWYYFA+ncWpcriJ7jO3yQWPTsZYkyOZpZ7rjkunTiaNL4GcBHi9tDasj9O3XFQUng/wlwOpzuiHG/T1DwPdBmMvSgjXKYVFbMGLXD/Q9gGQ=
-----END RSA PRIVATE KEY-----
            """,
            alipay_public_key_string="""-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvOFvNowlzvC3aIpzIf9Nn++qfgU77Sq++M1LZbraUmYQLa5ywI1UAE40tRcumNBkrO/uAAAexANTW8p+EVVf0vmvus1GnITwMq0wXpwQwulrWVhUwbKDWsgsO9wy+Z2hY7BH5Ll0TQwIh9FSPWyEmIzQ6DA+A5k8bCdEXYwwKaJWYIUBKAZPrDEAyE+tbsyPzfWplh5zKujz0tIHSvQqhZlhSct+sIko2Gf5fuJ+oFidLpFYy1rCLDhxoS3Sg53YaG4UH10Zvzcg+sWG9Q9eldPKkwlByq/cvpYglnIcc1pxOUvZu9rykMUGUcUxfErMluuOqFQVo6Ha3XDJyyebmwIDAQAB
-----END PUBLIC KEY-----""",
            sign_type="RSA2",
            debug=settings.ALIPAY_DEBUG
        )

        # 生成登录支付宝连接
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,
            total_amount=str(order.total_amount),
            subject="美多商城%s" % order_id,
            return_url=settings.ALIPAY_RETURN_URL,
        )

        # 响应登录支付宝连接
        # 真实环境电脑网站支付网关：https://openapi.alipay.com/gateway.do? + order_string
        # 沙箱环境电脑网站支付网关：https://openapi.alipaydev.com/gateway.do? + order_string
        alipay_url = settings.ALIPAY_URL + "?" + order_string
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'alipay_url': alipay_url})